package com.example.blog_system.service.impl;

import com.example.blog_system.dto.CommentDto;
import com.example.blog_system.entity.Article;
import com.example.blog_system.entity.Comment;
import com.example.blog_system.entity.User;
import com.example.blog_system.repository.ArticleRepository;
import com.example.blog_system.repository.CommentRepository;
import com.example.blog_system.repository.UserRepository;
import com.example.blog_system.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public CommentDto createComment(CommentDto commentDto, Long authorId) {
        User author = userRepository.findById(authorId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Article article = articleRepository.findById(commentDto.getArticleId())
                .orElseThrow(() -> new RuntimeException("文章不存在"));
        Comment comment = new Comment();
        comment.setContent(commentDto.getContent());
        comment.setArticle(article);
        comment.setAuthor(author);
        Comment saved = commentRepository.save(comment);
        return convertToDto(saved);
    }

    @Override
    @Transactional
    public void deleteComment(Long id, Long authorId) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("评论不存在"));
        if (!comment.getAuthor().getId().equals(authorId)) {
            throw new RuntimeException("无权删除此评论");
        }
        commentRepository.delete(comment);
    }

    @Override
    public Page<CommentDto> getCommentsByArticle(Long articleId, Pageable pageable) {
        return commentRepository.findByArticleId(articleId, pageable)
                .map(this::convertToDto);
    }

    @Override
    public Page<CommentDto> getCommentsByUser(Long userId, Pageable pageable) {
        return commentRepository.findByAuthorId(userId, pageable)
                .map(this::convertToDto);
    }

    private CommentDto convertToDto(Comment comment) {
        CommentDto dto = new CommentDto();
        dto.setId(comment.getId());
        dto.setContent(comment.getContent());
        dto.setArticleId(comment.getArticle().getId());
        dto.setAuthorId(comment.getAuthor().getId());
        dto.setAuthorName(comment.getAuthor().getUsername());
        dto.setCreatedAt(comment.getCreatedAt());
        dto.setUpdatedAt(comment.getUpdatedAt());
        return dto;
    }
}